package com.lemon.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lemon.domain.*;
import com.lemon.domain.dto.JianHuoDto;
import com.lemon.domain.vo.TransportVo;
import com.lemon.mapper.*;
import com.lemon.utils.UserThreadLocal;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lemon.service.OutboundOrderWeightsService;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class OutboundOrderWeightsServiceImpl extends ServiceImpl<OutboundOrderWeightsMapper, OutboundOrderWeights> implements OutboundOrderWeightsService{
    private final OutboundOrderMapper outboundOrderMapper;
    private final OutboundOrderDetailsMapper outboundOrderDetailsMapper;
    private final OutboundOrderPackageMapper outboundOrderPackageMapper;
    private final OutboundOrderWeightsMapper outboundOrderWeightsMapper;
    private final SkuMapper skuMapper;

    @Override
    public void transport(TransportVo transport) {
        OutboundOrderDetails outboundOrderDetails = outboundOrderDetailsMapper.selectById(transport.getId());
        outboundOrderDetails.setPrice(transport.getPrice());
        outboundOrderDetails.setLogisticsCompanyId(Long.valueOf(transport.getLogisticsCompanyId()));
        outboundOrderDetails.setLogisticsNumber(generateUnique8DigitNumber());
        outboundOrderDetails.setStatus(1);
        outboundOrderDetailsMapper.updateById(outboundOrderDetails);
    }

    /**
     * 生成8位不重复的随机数（基于时间戳）
     * @return 8位随机数字符串
     */
    public static String generateUnique8DigitNumber() {
        // 获取当前时间戳（毫秒）
        long timestamp = System.currentTimeMillis();

        // 取时间戳的后8位
        String timestampStr = String.valueOf(timestamp);
        if (timestampStr.length() >= 8) {
            return timestampStr.substring(timestampStr.length() - 8);
        } else {
            // 如果不足8位，在前面补随机数
            StringBuilder sb = new StringBuilder(timestampStr);
            while (sb.length() < 8) {
                sb.append((int) (Math.random() * 10));
            }
            return sb.toString();
        }
    }

    @Override
    public PageResult getPageTwo(Integer page, Integer pageSize, String invoiceCode) {
        List<Long> outboundOrderDetailIds = outboundOrderWeightsMapper.selectList(Wrappers.<OutboundOrderWeights>lambdaQuery()
                                                                                          .like(ObjectUtil.isNotEmpty(invoiceCode), OutboundOrderWeights::getWeightsCode, invoiceCode))
                                                    .stream()
                                                    .map(OutboundOrderWeights::getOutboundOrderDetailId)
                                                    .collect(Collectors.toList());

        // 如果没有匹配的记录，直接返回空结果
        if (outboundOrderDetailIds.isEmpty()) {
            return new PageResult(0L, new ArrayList<>());
        }

        // 开启分页
        PageHelper.startPage(page, pageSize);

        // 执行查询，PageHelper会自动对这个查询进行分页
        List<OutboundOrderDetails> outboundOrderDetails = outboundOrderDetailsMapper.selectList(Wrappers.<OutboundOrderDetails>lambdaQuery()
                                                                                                        .in(OutboundOrderDetails::getId, outboundOrderDetailIds)
                                                                                                        .eq(OutboundOrderDetails::getStatus, 3));

        List<JianHuoDto> list = new ArrayList<>();
        outboundOrderDetails.forEach(orderDetails -> {
            JianHuoDto jianHuoDto = new JianHuoDto();
            jianHuoDto.setId(orderDetails.getId());
            OutboundOrder outboundOrder = outboundOrderMapper.selectOne(Wrappers.<OutboundOrder>lambdaQuery()
                                                                                .eq(OutboundOrder::getId, orderDetails.getOutboundOrderId()));
            jianHuoDto.setInvoiceCode(outboundOrder.getInvoiceCode());
            jianHuoDto.setCode(orderDetails.getCode());
            Sku sku = skuMapper.selectById(orderDetails.getSkuId());
            jianHuoDto.setTitle(sku.getTitle());
            jianHuoDto.setPreCount(orderDetails.getPreCount());
            jianHuoDto.setProductWeight(sku.getProductWeight());
            jianHuoDto.setProductVolume(sku.getProductVolume());
            jianHuoDto.setCustomerId(outboundOrder.getCustomerId());
            jianHuoDto.setCreateTime(outboundOrder.getCreateTime());
            jianHuoDto.setPickEmpId(orderDetails.getPickEmpId());
            OutboundOrderPackage aPackage = outboundOrderPackageMapper.selectOne(Wrappers.<OutboundOrderPackage>lambdaQuery()
                                                                                         .eq(OutboundOrderPackage::getOutboundOrderDetailId, orderDetails.getId()));
            jianHuoDto.setPackEmpId(aPackage.getPackageEmpId());
            jianHuoDto.setPackTime(aPackage.getPackageTime());
            jianHuoDto.setStatus(orderDetails.getStatus());
            jianHuoDto.setLogisticsCompanyId(orderDetails.getLogisticsCompanyId());
            list.add(jianHuoDto);
        });

        // 获取分页信息并返回结果
        com.github.pagehelper.Page<OutboundOrderDetails> pageResult = (com.github.pagehelper.Page<OutboundOrderDetails>) outboundOrderDetails;
        return new PageResult(pageResult.getTotal(), list);
    }
    @Override
    public PageResult getPage(Integer page, Integer pageSize, String invoiceCode) {
        List<Long> outboundOrderDetailIds = outboundOrderWeightsMapper.selectList(Wrappers.<OutboundOrderWeights>lambdaQuery()
                                                                                          .like(ObjectUtil.isNotEmpty(invoiceCode), OutboundOrderWeights::getWeightsCode, invoiceCode))
                                                    .stream()
                                                    .map(OutboundOrderWeights::getOutboundOrderDetailId)
                                                    .collect(Collectors.toList());

        // 如果没有匹配的记录，直接返回空结果
        if (outboundOrderDetailIds.isEmpty()) {
            return new PageResult(0L, new ArrayList<>());
        }

        // 开启分页
        PageHelper.startPage(page, pageSize);

        // 执行查询，PageHelper会自动对这个查询进行分页
        List<OutboundOrderDetails> outboundOrderDetails = outboundOrderDetailsMapper.selectList(Wrappers.<OutboundOrderDetails>lambdaQuery()
                                                                                                        .in(OutboundOrderDetails::getId, outboundOrderDetailIds)
                                                                                                        .in(OutboundOrderDetails::getStatus, 0, 1, 2).orderByDesc(OutboundOrderDetails::getPickTime));

        List<JianHuoDto> list = new ArrayList<>();
        outboundOrderDetails.forEach(orderDetails -> {
            JianHuoDto jianHuoDto = new JianHuoDto();
            jianHuoDto.setId(orderDetails.getId());
            OutboundOrder outboundOrder = outboundOrderMapper.selectOne(Wrappers.<OutboundOrder>lambdaQuery()
                                                                                .eq(OutboundOrder::getId, orderDetails.getOutboundOrderId()));
            jianHuoDto.setInvoiceCode(outboundOrder.getInvoiceCode());
            jianHuoDto.setCode(orderDetails.getCode());
            Sku sku = skuMapper.selectById(orderDetails.getSkuId());
            jianHuoDto.setTitle(sku.getTitle());
            jianHuoDto.setPreCount(orderDetails.getPreCount());
            jianHuoDto.setProductWeight(sku.getProductWeight());
            jianHuoDto.setProductVolume(sku.getProductVolume());
            jianHuoDto.setCustomerId(outboundOrder.getCustomerId());
            jianHuoDto.setCreateTime(outboundOrder.getCreateTime());
            jianHuoDto.setPickEmpId(orderDetails.getPickEmpId());
            OutboundOrderPackage aPackage = outboundOrderPackageMapper.selectOne(Wrappers.<OutboundOrderPackage>lambdaQuery()
                                                                                         .eq(OutboundOrderPackage::getOutboundOrderDetailId, orderDetails.getId()));
            jianHuoDto.setPackEmpId(aPackage.getPackageEmpId());
            jianHuoDto.setPackTime(aPackage.getPackageTime());
            jianHuoDto.setStatus(orderDetails.getStatus());
            jianHuoDto.setLogisticsCompanyId(orderDetails.getLogisticsCompanyId());
            list.add(jianHuoDto);
        });

        // 获取分页信息并返回结果
        com.github.pagehelper.Page<OutboundOrderDetails> pageResult = (com.github.pagehelper.Page<OutboundOrderDetails>) outboundOrderDetails;
        return new PageResult(pageResult.getTotal(), list);
    }


    @Override
    @Transactional
    public void chengZhong(Long id) {
        OutboundOrderPackage aPackage = outboundOrderPackageMapper.selectById(id);
        OutboundOrderWeights outboundOrderWeights = outboundOrderWeightsMapper.selectOne(Wrappers.<OutboundOrderWeights>lambdaQuery().eq(OutboundOrderWeights::getOutboundOrderDetailId, aPackage.getOutboundOrderDetailId()));
        outboundOrderWeights.setWeightsTime(LocalDateTime.now());
        outboundOrderWeights.setWeightsEmpId(UserThreadLocal.get().getId());
        outboundOrderWeights.setStatus(2);
        OutboundOrderDetails outboundOrderDetails = outboundOrderDetailsMapper.selectById(aPackage.getOutboundOrderDetailId());
        OutboundOrder outboundOrder = outboundOrderMapper.selectById(outboundOrderDetails.getOutboundOrderId());
        outboundOrder.setStatus(7);
        outboundOrderMapper.updateById(outboundOrder);
        outboundOrderWeightsMapper.updateById(outboundOrderWeights);
    }
}
